package com.banach.prema.im.callback;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.banach.prema.im.annotation.CallbackCommand;
import com.banach.prema.im.annotation.Callback;
import com.banach.prema.im.config.AppConfig;
import com.banach.prema.im.rest.GroupRestApi;
import com.banach.prema.repository.GroupMsgRepository;
import com.banach.prema.repository.GroupRepository;
import com.banach.prema.repository.dataobject.GroupDO;
import com.banach.prema.repository.dataobject.GroupMsgDO;
import com.ego.framework.core.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 群组系统回调服务
 * @author ajun
 *
 */
@Service
@Callback
public class GroupCallBackService {
	private final static CallBackResponse SUCCESS_RESPONSE = CallBackResponse.createSuccessResponse();
	@Autowired
	private GroupMsgRepository groupMsgRepository;

	@Autowired
	private GroupRepository groupRepository;
	@Autowired
	private GroupRestApi groupRestApi;
	@Autowired
	private AppConfig appConfig;
	private static final Logger log = LoggerFactory.getLogger(GroupCallBackService.class);
	/**
	 * 创建群组之前回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackBeforeCreateGroup")
	public CallBackResponse beforeCreateGroup(JSONObject json){
		System.out.println("创建群组之前"+json.toJSONString());
		return SUCCESS_RESPONSE;
	}
	
	/**
	 * 创建群组之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterCreateGroup")
	public CallBackResponse afterCreateGroup(JSONObject json){
		GroupDO group = groupRepository.selectById(json.getString("GroupId"));
		if(group ==null){
			group = JSON.parseObject(json.toJSONString(), GroupDO.class);
			group.setId(json.getString("GroupId"));
			groupRepository.create(group);
		}
		String type = json.getString("Type");
		if("private".equalsIgnoreCase(type)) {
			JSONObject res = groupRestApi.modifyGroupFaceUrl(json.getString("GroupId"),  appConfig.getUrl()+"/images/im/team.jpg");
			log.info(res.toJSONString());
		}
		return SUCCESS_RESPONSE;
	}
	
	/**
	 * 申请入群之前回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackBeforeApplyJoinGroup")
	public CallBackResponse beforeApplyJoinGroup(JSONObject json){
		
		return SUCCESS_RESPONSE;
	}
	
	/**
	 * 拉人入群之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackBeforeInviteJoinGroup")
	public CallBackResponse beforeInviteJoinGroup(JSONObject json){
		
		return SUCCESS_RESPONSE;
	}
	
	/**
	 * 新成员入群之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterNewMemberJoin")
	public CallBackResponse afterNewMemberJoin(JSONObject json){
		GroupDO group = groupRepository.selectById(json.getString("GroupId"));
		JSONArray memberList = JSON.parseArray(group.getMemberList());
		JSONArray  newMemberList = json.getJSONArray("NewMemberList");
		memberList.addAll(newMemberList);
		group.setMemberList(memberList.toJSONString());
		groupRepository.update(group);
		groupRestApi.updateGroupName(json.getString("GroupId"), group.getName()+"("+memberList.size()+")");
		return SUCCESS_RESPONSE;
	}

	/**
	 * 群成员离开之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterMemberExit")
	public CallBackResponse afterMemberExit(JSONObject json){
		GroupDO group = groupRepository.selectById(json.getString("GroupId"));
		
		JSONArray memberList = JSON.parseArray(group.getMemberList());
		JSONArray  exitMemberList = json.getJSONArray("ExitMemberList");
		exitMemberList:
		for(int i=0;i<exitMemberList.size();i++) {
			for(int k=0;k<memberList.size();k++) {
				if(memberList.getJSONObject(k).getString("Member_Account").equals(exitMemberList.getJSONObject(i).getString("Member_Account"))) {
					memberList.remove(k);
					continue exitMemberList;
				}
			}
		}
		group.setMemberList(memberList.toJSONString());
		groupRepository.update(group);
		groupRestApi.updateGroupName(json.getString("GroupId"), group.getName()+"("+memberList.size()+")");
		return SUCCESS_RESPONSE;
	}

	
	/**
	 *群内发言之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterSendMsg")
	public CallBackResponse afterSendMsg(String text){
		GroupMsgDO msg = JSON.parseObject(text, GroupMsgDO.class);
		groupMsgRepository.update(msg);
		GroupDO group = groupRepository.selectById(msg.getGroupId());
		if(group !=null){
			group.setLastActiveTime(new Date());
			groupRepository.update(group);
		}
		return SUCCESS_RESPONSE;
	}
	
	/**
	 *群组满员之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterGroupFull")
	public CallBackResponse afterGroupFull(JSONObject json){
		
		return SUCCESS_RESPONSE;
	}
	
	/**
	 *群组解散之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterGroupDestroyed")
	public CallBackResponse afterGroupDestroyed(JSONObject json){
		GroupDO group = groupRepository.selectById(json.getString("GroupId"));
		if(group !=null){
			group.setValid(false);
			groupRepository.update(group);
		}
		return SUCCESS_RESPONSE;
	}
	
	/**
	 *群组资料修改之后回调
	 * @return
	 */
	@CallbackCommand("Group.CallbackAfterGroupInfoChanged")
	public CallBackResponse afterGroupInfoChanged(JSONObject json){
		GroupDO group = groupRepository.selectById(json.getString("GroupId"));
		if(group !=null){
			if(StringUtils.isNotEmpty(json.getString("Name"))){
				String exp = "\\(\\d\\)";
				Pattern p = Pattern.compile(exp, Pattern.CASE_INSENSITIVE);
				String name = json.getString("Name");
				Matcher matcher = p.matcher(name);
				name = matcher.replaceAll("");
				group.setName(name);
			}
			if(StringUtils.isNotEmpty(json.getString("Notification"))){
				group.setNotice(json.getString("Notification"));
			}
			if(StringUtils.isNotEmpty(json.getString("Introduction"))){
				group.setIntro(json.getString("Introduction"));
			}
			groupRepository.update(group);
		}
		return SUCCESS_RESPONSE;
	}

}
